﻿using Microsoft.Extensions.DependencyInjection;
using Modules.Cms.Entitys;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Repositories;
using PmSoft.Utilities;

namespace Modules.Cms.Repositories;


[UseDI(ServiceLifetime.Scoped)]
public class CmsDealerRepository : Repository<CmsDealer, DefaultDbContext>
{
    public CmsDealerRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
    {
    }
    public IPagedList<CmsDealer> GetCmsDealers(CmsDealerQuery query, int pageIndex, int pageSize) {
        Sql sql = Sql.Builder;
        sql.Select("id")
            .From("cms_dealer")
            .Where("is_deleted=0");
        if (!string.IsNullOrEmpty(query.Keywords))
            sql.Where("(name Like @0 or phone Like @0 or area_name Like @0)", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
        sql.OrderBy("create_dt DESC");
        var result = GetPagingEntities(pageSize, pageIndex, sql);
        return result;
    }

    public CmsDealer? GetDalerByUserId(int userId)
    {
        Sql sql = Sql.Builder.Select("id").From("cms_dealer").Where("user_id=@0", userId);
        var id = DbContext.FirstOrDefault<int>(sql);
        if (id == 0)
            return null;
        return Get(id);
    }
}
